package com.weijian.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weijian.common.pojo.CommonResult;
import com.weijian.common.pojo.PageResponse;
import com.weijian.dal.dataobject.Article;
import com.weijian.dal.query.ArticlePageQuery;
import com.weijian.dal.vo.ArticlePageReqVO;
import com.weijian.service.ArticleService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.weijian.common.pojo.CommonResult.success;


@RestController
@RequestMapping("/doc")
@Validated
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @PostMapping("/create")
    @Operation(summary = "新增")
    @PermitAll
    public CommonResult<Long> create(@Valid @RequestBody Article entity) {
        articleService.save(entity);
        return success(entity.getId());
    }

    @PutMapping("update")
    @Operation(summary = "修改")
    @PermitAll
    public CommonResult<Boolean> update(@Valid @RequestBody Article reqVO) {
        articleService.updateById(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除")
    @PermitAll
    public CommonResult<Boolean> delete(@RequestParam("id") Long id) {
        articleService.removeById(id);
        return success(true);
    }

    @PostMapping("/list")
    @Operation(summary = "分页")
    @PermitAll
    public CommonResult<PageResponse<ArticlePageReqVO>> getPage(@RequestBody ArticlePageQuery query) {
        // 获得分页列表
        Page<Article> ArticlePage = articleService.lambdaQuery()
                .like(StrUtil.isNotBlank(query.getTitle()), Article::getTitle, query.getTitle())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        return success(PageResponse.of(ArticlePage, ArticlePageReqVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "详情")
    @PermitAll
    public CommonResult<Article> get(@RequestParam("id") Long id) {
        Article entity = articleService.getById(id);
        if (entity == null) {
            return success(null);
        }
        return success(entity);
    }

}
